<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图书馆管理系统 - 我的费用</title>
    <link rel="stylesheet" href="styles.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <script src="auth.js"></script>
    <script src="permission-control.js"></script>
</head>
<body>
    <!-- 主系统页面 -->
    <div id="mainPage" class="page active">
        <!-- 顶部导航栏 -->
        <header class="header">
            <div class="header-left">
                <button class="sidebar-toggle" onclick="toggleSidebar()">
                    <i class="fas fa-bars"></i>
                </button>
                <h1 class="logo">
                    <i class="fas fa-book"></i>
                    图书馆管理系统
                </h1>
            </div>
            <div class="header-right">
                <div class="notification-icon" onclick="showNotifications()">
                    <i class="fas fa-bell"></i>
                    <span class="notification-badge" id="notificationBadge">0</span>
                </div>
                <div class="user-menu">
                    <span class="user-name" id="currentUserName">用户</span>
                    <div class="user-dropdown">
                        <button class="dropdown-btn">
                            <i class="fas fa-user-circle"></i>
                            <i class="fas fa-chevron-down"></i>
                        </button>
                        <div class="dropdown-content">
                            <a href="#" onclick="showProfile()">个人资料</a>
                            <a href="#" onclick="changePassword()">修改密码</a>
                            <a href="#" onclick="logout()">退出登录</a>
                        </div>
                    </div>
                </div>
            </div>
        </header>

        <!-- 侧边栏 -->
        <aside class="sidebar" id="sidebar">
            <nav class="sidebar-nav">
                <ul id="sidebarMenu">
                    <!-- 菜单将通过JavaScript动态生成 -->
                </ul>
            </nav>
        </aside>

        <!-- 主内容区域 -->
        <main class="main-content">
            <!-- 我的费用页面 -->
            <div id="myPayments" class="content-page active">
                <div class="page-header">
                    <h2>我的费用</h2>
                    <div class="header-actions">
                        <button class="btn btn-info" onclick="loadMyPayments()">
                            <i class="fas fa-refresh"></i>
                            刷新
                        </button>
                    </div>
                </div>
                
                <!-- 费用统计 -->
                <div class="stats">
                    <div class="stat-card">
                        <div class="stat-label">待缴费用</div>
                        <div class="stat-value" id="unpaidAmount">¥0.00</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-label">已缴费用</div>
                        <div class="stat-value" id="paidAmount">¥0.00</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-label">总费用</div>
                        <div class="stat-value" id="totalAmount">¥0.00</div>
                    </div>
                </div>

                <!-- 搜索和筛选 -->
                <div class="search-filters">
                    <div class="search-group">
                        <input type="text" id="paymentSearch" class="form-control" placeholder="搜索费用记录...">
                        <button class="btn btn-primary" onclick="searchPayments()">
                            <i class="fas fa-search"></i>
                            搜索
                        </button>
                    </div>
                    <div class="filter-group">
                        <select id="paymentStatusFilter" class="form-control" onchange="loadMyPayments()">
                            <option value="">全部状态</option>
                            <option value="unpaid">待缴费</option>
                            <option value="paid">已缴费</option>
                        </select>
                        <select id="paymentTypeFilter" class="form-control" onchange="loadMyPayments()">
                            <option value="">全部类型</option>
                            <option value="overdue_fine">逾期罚款</option>
                            <option value="damage_fee">损坏赔偿</option>
                            <option value="lost_fee">丢失赔偿</option>
                        </select>
                    </div>
                </div>

                <!-- 费用列表 -->
                <div class="table-container">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>费用ID</th>
                                <th>费用类型</th>
                                <th>相关图书</th>
                                <th>费用金额</th>
                                <th>产生时间</th>
                                <th>缴费时间</th>
                                <th>状态</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="paymentsTableBody">
                            <tr>
                                <td colspan="8" class="text-center">暂无数据</td>
                            </tr>
                        </tbody>
                    </table>
                </div>

                <!-- 分页 -->
                <div class="pagination-container">
                    <div id="paginationInfo" class="pagination-info"></div>
                    <div id="pagination" class="pagination"></div>
                    <div id="paginationTools" class="pagination-tools"></div>
                </div>
            </div>
        </main>
    </div>

    <!-- 加载提示 -->
    <div id="loadingOverlay" class="loading-overlay">
        <div class="loading-spinner">
            <i class="fas fa-spinner fa-spin"></i>
            <p>加载中...</p>
        </div>
    </div>

    <!-- 消息提示 -->
    <div id="messageContainer" class="message-container">
    </div>

    <!-- 费用详情模态框 -->
    <div id="modalOverlay" class="modal-overlay">
        <div class="modal">
            <div class="modal-header">
                <h3 id="modalTitle">费用详情</h3>
                <button class="modal-close" onclick="closeModal()">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div class="modal-body" id="modalBody">
                <!-- 内容将通过JavaScript动态生成 -->
            </div>
            <div class="modal-footer" id="modalFooter">
                <!-- 按钮将通过JavaScript动态生成 -->
            </div>
        </div>
    </div>

    <script src="config.js"></script>
    <script>
        // API基础配置
        const API_BASE_URL = 'http://118.31.223.190:8080';

        // 通用API请求函数
        class ApiClient {
            constructor() {
                this.baseURL = API_BASE_URL;
            }

            async request(url, options = {}) {
                const isForm = options && options.body instanceof FormData;
                const headers = isForm ? (options.headers || {}) : { 'Content-Type': 'application/json', ...(options.headers || {}) };
                const config = { headers, ...options };

                try {
                    const response = await fetch(`${this.baseURL}${url}`, config);
                    const data = await response.json();
                    
                    if (!response.ok) {
                        throw new Error(data.message || `HTTP error! status: ${response.status}`);
                    }
                    
                    return data;
                } catch (error) {
                    console.error('API请求失败:', error);
                    throw error;
                }
            }

            async get(url, params = {}) {
                const queryString = new URLSearchParams(params).toString();
                const fullUrl = queryString ? `${url}?${queryString}` : url;
                return this.request(fullUrl, { method: 'GET' });
            }

            async post(url, data = {}) {
                if (data instanceof FormData) {
                    return this.request(url, { method: 'POST', body: data });
                }
                return this.request(url, { method: 'POST', body: JSON.stringify(data) });
            }

            async put(url, data = {}) {
                return this.request(url, {
                    method: 'PUT',
                    body: JSON.stringify(data)
                });
            }

            async delete(url) {
                return this.request(url, { method: 'DELETE' });
            }
        }

        // 创建API客户端实例
        const api = new ApiClient();

        // 费用API
        const FeeAPI = {
            // 获取用户费用列表
            getUserFeeRecords: (userId, params = {}) => api.get(`/api/fees/user/${userId}`, params),
            
            // 获取用户费用统计
            getUserFeeStats: (userId) => api.get(`/api/fees/user/${userId}/stats`),
            
            // 缴费
            payFee: (feeId, payMethod) => api.post(`/api/fees/${feeId}/pay?payMethod=${payMethod}`)
        };

        // 通知API
        const NotificationAPI = {
            countUnreadNotifications: (userId) => api.get(`/api/notifications/user/${userId}/unread-count`)
        };

        // 工具函数
        const Utils = {
            // 显示加载状态
            showLoading: () => {
                const loadingOverlay = document.getElementById('loadingOverlay');
                if (loadingOverlay) {
                    loadingOverlay.classList.add('active');
                }
            },

            // 隐藏加载状态
            hideLoading: () => {
                const loadingOverlay = document.getElementById('loadingOverlay');
                if (loadingOverlay) {
                    loadingOverlay.classList.remove('active');
                }
            },

            // 显示消息提示
            showMessage: (message, type = 'info', duration = 3000) => {
                const messageContainer = document.getElementById('messageContainer');
                if (!messageContainer) return;

                const messageEl = document.createElement('div');
                messageEl.className = `message ${type}`;
                
                const iconMap = {
                    success: 'fas fa-check-circle',
                    error: 'fas fa-exclamation-circle',
                    warning: 'fas fa-exclamation-triangle',
                    info: 'fas fa-info-circle'
                };

                messageEl.innerHTML = `
                    <i class="${iconMap[type] || iconMap.info}"></i>
                    <span>${message}</span>
                    <button class="message-close" onclick="this.parentElement.remove()">
                        <i class="fas fa-times"></i>
                    </button>
                `;

                messageContainer.appendChild(messageEl);

                // 自动移除消息
                setTimeout(() => {
                    if (messageEl.parentElement) {
                        messageEl.remove();
                    }
                }, duration);
            },

            // 格式化日期
            formatDate: (dateStr) => {
                if (!dateStr) return '-';
                const date = new Date(dateStr);
                return date.toLocaleString('zh-CN');
            },

            // 格式化金额
            formatAmount: (amount) => {
                return `¥${parseFloat(amount || 0).toFixed(2)}`;
            },

            // 获取费用类型文本
            getPaymentTypeText: (type) => {
                const typeMap = {
                    'overdue_fine': '逾期罚款',
                    'damage_fee': '损坏赔偿',
                    'lost_fee': '丢失赔偿'
                };
                return typeMap[type] || type;
            },

            // 获取状态文本
            getStatusText: (status) => {
                const statusMap = {
                    'unpaid': '待缴费',
                    'paid': '已缴费'
                };
                return statusMap[status] || status;
            },

            // 创建分页组件
            createPagination: (currentPage, totalPages, onPageChange) => {
                const pagination = document.createElement('div');
                pagination.className = 'pagination';
                
                // 上一页
                const prevBtn = document.createElement('button');
                prevBtn.className = `btn btn-sm ${currentPage === 1 ? 'btn-secondary' : 'btn-primary'}`;
                prevBtn.disabled = currentPage === 1;
                prevBtn.innerHTML = '<i class="fas fa-chevron-left"></i>';
                prevBtn.onclick = () => currentPage > 1 && onPageChange(currentPage - 1);
                pagination.appendChild(prevBtn);
                
                // 页码
                const startPage = Math.max(1, currentPage - 2);
                const endPage = Math.min(totalPages, currentPage + 2);
                
                for (let i = startPage; i <= endPage; i++) {
                    const pageBtn = document.createElement('button');
                    pageBtn.className = `btn btn-sm ${i === currentPage ? 'btn-primary' : 'btn-outline-primary'}`;
                    pageBtn.textContent = i;
                    pageBtn.onclick = () => onPageChange(i);
                    pagination.appendChild(pageBtn);
                }
                
                // 下一页
                const nextBtn = document.createElement('button');
                nextBtn.className = `btn btn-sm ${currentPage === totalPages ? 'btn-secondary' : 'btn-primary'}`;
                nextBtn.disabled = currentPage === totalPages;
                nextBtn.innerHTML = '<i class="fas fa-chevron-right"></i>';
                nextBtn.onclick = () => currentPage < totalPages && onPageChange(currentPage + 1);
                pagination.appendChild(nextBtn);
                
                return pagination;
            }
        };

        // 全局变量
        let currentUser = null;
        let currentPageNum = 1;
        let currentPageSize = 10;
        let totalPages = 1;

        // 页面初始化
        document.addEventListener('DOMContentLoaded', function() {
            setTimeout(() => {
                initializeApp();
            }, 100);
        });

        // 初始化应用
        async function initializeApp() {
            try {
                // 使用通用权限检查
                if (!initializePagePermission()) {
                    return;
                }
                
                currentUser = authManager.getCurrentUser();
                
                // 生成动态菜单
                generateSidebarMenu();
                
                // 更新用户信息
                document.getElementById('currentUserName').textContent = currentUser.realName || currentUser.username;
                
                // 加载我的费用数据
                await loadMyPayments();
                
                // 加载统计数据
                await loadMyPaymentStats();
                
                // 加载未读通知数量
                await loadUnreadNotificationCount();
            } catch (error) {
                console.error('初始化应用失败:', error);
                Utils.showMessage('初始化应用失败', 'error');
            }
        }

        // 生成侧边栏菜单
        function generateSidebarMenu() {
            const sidebarMenu = document.getElementById('sidebarMenu');
            if (sidebarMenu) {
                sidebarMenu.innerHTML = authManager.generateSidebarMenu();
            }
        }

        // 切换侧边栏
        function toggleSidebar() {
            const sidebar = document.getElementById('sidebar');
            sidebar.classList.toggle('active');
        }

        // 退出登录
        function logout() {
            authManager.logout();
        }

        // 显示通知
        function showNotifications() {
            window.location.href = 'notifications.html';
        }

        // 显示个人资料
        function showProfile() {
            Utils.showMessage('个人资料功能开发中', 'info');
        }

        // 修改密码
        function changePassword() {
            Utils.showMessage('修改密码功能开发中', 'info');
        }

        // 加载未读通知数量
        async function loadUnreadNotificationCount() {
            try {
                const response = await NotificationAPI.countUnreadNotifications(currentUser.userId);
                if (response.result === 'SUCCESS') {
                    const badge = document.getElementById('notificationBadge');
                    if (badge) {
                        badge.textContent = response.data || 0;
                        badge.style.display = response.data > 0 ? 'block' : 'none';
                    }
                }
            } catch (error) {
                console.error('Load unread notification count error:', error);
            }
        }

        // 加载我的费用数据
        async function loadMyPayments(page = 1) {
            try {
                Utils.showLoading();
                
                const keyword = document.getElementById('paymentSearch')?.value || '';
                let status = document.getElementById('paymentStatusFilter')?.value || '';
                let type = document.getElementById('paymentTypeFilter')?.value || '';
                
                if (status === '') status = undefined;
                if (type === '') type = undefined;
                
                const params = {
                    page: page,
                    size: currentPageSize,
                    feeType: type,
                    status: status
                };
                
                // 移除undefined值
                Object.keys(params).forEach(key => params[key] === undefined && delete params[key]);
                
                const response = await FeeAPI.getUserFeeRecords(currentUser.userId, params);
                
                if (response.result === 'SUCCESS') {
                    const data = response.data;
                    renderPaymentsTable(data.records || []);
                    
                    // 更新分页信息
                    currentPageNum = data.current || 1;
                    totalPages = data.pages || 1;
                    renderPagination('pagination', currentPageNum, totalPages, loadMyPayments);
                    renderPaginationInfo('paginationInfo', data);
                    renderPaginationTools('paginationTools', totalPages, 
                        (page) => loadMyPayments(page),
                        (size) => {
                            currentPageSize = size;
                            loadMyPayments(1);
                        }
                    );
                } else {
                    Utils.showMessage(response.message || '加载费用数据失败', 'error');
                }
            } catch (error) {
                Utils.showMessage('加载费用数据失败', 'error');
                console.error('Load payments error:', error);
            } finally {
                Utils.hideLoading();
            }
        }

        // 加载费用统计
        async function loadMyPaymentStats() {
            try {
                const response = await FeeAPI.getUserFeeStats(currentUser.userId);
                if (response.result === 'SUCCESS') {
                    const stats = response.data;
                    document.getElementById('unpaidAmount').textContent = Utils.formatAmount(stats.unpaidAmount);
                    document.getElementById('paidAmount').textContent = Utils.formatAmount(stats.paidAmount);
                    document.getElementById('totalAmount').textContent = Utils.formatAmount(stats.totalAmount);
                }
            } catch (error) {
                console.error('Load payment stats error:', error);
            }
        }

        // 渲染费用表格
        function renderPaymentsTable(payments) {
            const tbody = document.getElementById('paymentsTableBody');
            
            if (!payments || payments.length === 0) {
                tbody.innerHTML = '<tr><td colspan="8" class="text-center">暂无数据</td></tr>';
                return;
            }
            
            tbody.innerHTML = payments.map(payment => `
                <tr>
                    <td>${payment.feeId}</td>
                    <td>${Utils.getPaymentTypeText(payment.feeType)}</td>
                    <td>${payment.bookName || '-'}</td>
                    <td class="amount">${Utils.formatAmount(payment.amount)}</td>
                    <td>${Utils.formatDate(payment.createTime)}</td>
                    <td>${Utils.formatDate(payment.payTime)}</td>
                    <td>
                        <span class="status-badge status-${payment.status}">
                            ${Utils.getStatusText(payment.status)}
                        </span>
                    </td>
                    <td>
                        <button class="btn btn-sm btn-info" onclick="viewPaymentDetail(${payment.feeId})">
                            <i class="fas fa-eye"></i>
                            详情
                        </button>
                        ${payment.status === 'unpaid' ? `
                            <button class="btn btn-sm btn-success" onclick="payFee(${payment.feeId})">
                                <i class="fas fa-credit-card"></i>
                                缴费
                            </button>
                        ` : ''}
                    </td>
                </tr>
            `).join('');
        }

        // 搜索费用
        function searchPayments() {
            loadMyPayments(1);
        }

        // 查看费用详情
        async function viewPaymentDetail(feeId) {
            // 从当前表格中获取费用详情（简化实现）
            const tableRows = document.querySelectorAll('#paymentsTableBody tr');
            let payment = null;
            
            for (let row of tableRows) {
                const cells = row.querySelectorAll('td');
                if (cells.length > 0 && cells[0].textContent == feeId) {
                    payment = {
                        feeId: cells[0].textContent,
                        feeType: cells[1].textContent,
                        bookName: cells[2].textContent,
                        amount: cells[3].textContent,
                        createTime: cells[4].textContent,
                        payTime: cells[5].textContent,
                        status: cells[6].querySelector('.status-badge').textContent.trim()
                    };
                    break;
                }
            }
            
            if (payment) {
                showModal('费用详情', `
                    <div class="detail-container">
                        <div class="detail-row">
                            <label>费用ID:</label>
                            <span>${payment.feeId}</span>
                        </div>
                        <div class="detail-row">
                            <label>费用类型:</label>
                            <span>${payment.feeType}</span>
                        </div>
                        <div class="detail-row">
                            <label>相关图书:</label>
                            <span>${payment.bookName}</span>
                        </div>
                        <div class="detail-row">
                            <label>费用金额:</label>
                            <span class="amount">${payment.amount}</span>
                        </div>
                        <div class="detail-row">
                            <label>产生时间:</label>
                            <span>${payment.createTime}</span>
                        </div>
                        <div class="detail-row">
                            <label>缴费时间:</label>
                            <span>${payment.payTime}</span>
                        </div>
                        <div class="detail-row">
                            <label>状态:</label>
                            <span class="status-badge status-${payment.status.toLowerCase()}">${payment.status}</span>
                        </div>
                    </div>
                `, `
                    <button class="btn btn-secondary" onclick="closeModal()">关闭</button>
                    ${payment.status === '待缴费' ? `
                        <button class="btn btn-success" onclick="closeModal(); payFee(${payment.feeId})">
                            <i class="fas fa-credit-card"></i>
                            立即缴费
                        </button>
                    ` : ''}
                `);
            } else {
                Utils.showMessage('获取费用详情失败', 'error');
            }
        }

        // 缴费
        async function payFee(feeId) {
            if (!confirm('确定要缴纳此费用吗？')) {
                return;
            }
            
            try {
                Utils.showLoading();
                const response = await FeeAPI.payFee(feeId, 'alipay'); // 默认使用支付宝
                
                if (response.result === 'SUCCESS') {
                    Utils.showMessage('缴费成功', 'success');
                    // 重新加载数据
                    await loadMyPayments(currentPageNum);
                    await loadMyPaymentStats();
                } else {
                    Utils.showMessage(response.message || '缴费失败', 'error');
                }
            } catch (error) {
                Utils.showMessage('缴费失败', 'error');
            } finally {
                Utils.hideLoading();
            }
        }

        // 显示模态框
        function showModal(title, body, footer) {
            document.getElementById('modalTitle').textContent = title;
            document.getElementById('modalBody').innerHTML = body;
            document.getElementById('modalFooter').innerHTML = footer;
            document.getElementById('modalOverlay').classList.add('active');
        }

        // 关闭模态框
        function closeModal() {
            document.getElementById('modalOverlay').classList.remove('active');
        }

        // 渲染分页组件
        function renderPagination(containerId, currentPage, totalPages, onPageChange) {
            const container = document.getElementById(containerId);
            if (!container) return;
            
            if (totalPages <= 1) {
                container.innerHTML = '';
                return;
            }
            
            container.innerHTML = '';
            container.appendChild(Utils.createPagination(currentPage, totalPages, onPageChange));
        }

        // 渲染分页信息
        function renderPaginationInfo(containerId, data) {
            const container = document.getElementById(containerId);
            if (!container) return;
            
            const start = (data.current - 1) * data.size + 1;
            const end = Math.min(data.current * data.size, data.total);
            container.textContent = `显示 ${start}-${end} 条，共 ${data.total} 条`;
        }

        // 渲染分页工具栏
        function renderPaginationTools(containerId, totalPages, onJump, onSizeChange) {
            const container = document.getElementById(containerId);
            if (!container) return;
            
            container.innerHTML = `
                <span>到第</span>
                <input id="${containerId}-jump" type="number" min="1" max="${totalPages}" value="${currentPageNum}" style="width:60px">
                <span>页</span>
                <button id="${containerId}-go" class="btn btn-sm btn-primary">确定</button>
                <span style="margin-left:12px">每页</span>
                <select id="${containerId}-size" style="width:90px">
                    <option ${currentPageSize==10?'selected':''} value="10">10 条/页</option>
                    <option ${currentPageSize==20?'selected':''} value="20">20 条/页</option>
                    <option ${currentPageSize==50?'selected':''} value="50">50 条/页</option>
                    <option ${currentPageSize==100?'selected':''} value="100">100 条/页</option>
                </select>
            `;
            
            const goBtn = document.getElementById(`${containerId}-go`);
            const jumpInput = document.getElementById(`${containerId}-jump`);
            const sizeSelect = document.getElementById(`${containerId}-size`);
            
            if (goBtn && jumpInput) {
                goBtn.onclick = () => {
                    const page = parseInt(jumpInput.value || '1', 10);
                    const validPage = Math.min(Math.max(1, page), totalPages);
                    onJump(validPage);
                };
            }
            
            if (sizeSelect) {
                sizeSelect.onchange = () => {
                    const size = parseInt(sizeSelect.value, 10);
                    onSizeChange(size);
                };
            }
        }
    </script>
</body>
</html>